<?php
class Zendvn_Models_InvoiceDetail extends Zend_Db_Table{
	protected $_name = 'invoice_detail';
	protected $_primary = 'id';
	public function listItem($arrParam = null, $options = null){
		if($options['task'] == 'admin-list'){
			$db 	= $this	-> getAdapter();
			$select = $db 	-> select()
							-> from('invoice_detail AS ind',array('id','product_id','quantity','price','invoice_id'))
							-> joinLeft('invoice AS in','in.id = ind.invoice_id',
										array('in.email AS email','in.phone AS phone','in.address AS address',
											  'in.full_name AS full_name','in.created AS created','in.comment AS comment'
											  ))
							-> joinLeft('products AS p','p.id = ind.product_id',array('p.name AS product_name'))
							-> order('id DESC');
			$result = $db -> fetchAll($select);
			return $result;
		}
	}
	
	public function saveItem($arrParam = null, $options = null){		
		if($options == null){
			if(count($arrParam['cart'])>0){
				$i = 1;
				foreach ($arrParam['cart'] as $key => $val){
					if($i  == 1 ){
						$ids .=  $key;
					}else{
						$ids .=  ',' . $key;
					}
					$i ++;
				}
								
				$db = Zend_Registry::get('connectDb');
				$select = $db->select()
							 ->from('products as p',array('id','price'))							
							 ->where('p.id IN (' . $ids . ')');
				$result = $db->fetchAll($select);
				$tmp = array();				
				$cart = $arrParam['cart'];			
				foreach ($result as $key => $val){					
					$val['quantity'] = $cart[$val['id']];
					$tmp[] = $val;
				}				
			}
	
			foreach ($tmp as $key_1 => $info){
				$row =  $this->fetchNew();
				$row->product_id 	= $info['id'];
				$row->quantity 		= $info['quantity'];
				$row->price 		= $info['price'];
				$row->invoice_id	= $arrParam['invoice_id'];
				$row->save();
			}
			
		}
	}
	public function deleteItem($arrParam = null, $options = null){
		if($options['task'] == 'admin-delete'){
			$where = ' id = ' . $arrParam['id'];
			$row = $this->fetchRow($where);
			$this->delete($where);
		}		
		if($options['task'] == 'admin-multi-delete'){
			$cid = $arrParam['cid'];
			if(count($cid)>0){				
				$ids = implode(',',$cid);			
				$db = $this->getAdapter();
				$where = 'id IN (' . $ids . ')';
				$this->delete($where);
			}
		}
	}
}